package com.qqtech.qquan.mall.controller;

import java.math.BigDecimal;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.mall.enums.MallConst;
import com.qqtech.qquan.mall.enums.MallShopSendDeliveryTypeDictEnum;
import com.qqtech.qquan.mall.enums.MallShopStyleDictEnum;
import com.qqtech.qquan.mall.enums.MallShopTypeDictEnum;
import com.qqtech.qquan.mall.model.MallOrder;
import com.qqtech.qquan.mall.model.MallOrderQuery;
import com.qqtech.qquan.mall.model.MallOrderVo;
import com.qqtech.qquan.mall.model.MallProduct;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.model.MallShopVo;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.mall.service.MallOrderService;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallProductSpecService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseReturnStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderConst;
import com.qqtech.qquan.order.enums.OrderDeliverySendDeliveryTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderDeliveryTypeDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.service.OrderBaseService;
import com.qqtech.qquan.order.service.OrderHandleService;
import com.qqtech.qquan.sales.enums.SalesBaseTargetDictEnum;
import com.qqtech.qquan.sales.model.SalesBaseVo;
import com.qqtech.qquan.sales.service.SalesBaseService;
import com.qqtech.qquan.send.service.SendDeliveryOrderService;
import com.qqtech.qquan.user.model.UserAddressVo;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.service.UserAddressService;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/mall/order")
public class MallOrderController extends BaseWebController<MallOrder, MallOrderQuery> {
	@Resource
	private MallOrderService mallOrderService;

	@Resource
	private UserAddressService userAddressService;

	@Resource
	private OrderHandleService orderHandleService;

	@Resource
	private OrderBaseService orderBaseService;

	@Resource
	private SalesBaseService salesBaseService;

	@Resource
	private SendDeliveryOrderService sendDeliveryOrderService;

	@Resource
	private MallSupplierService mallSupplierService;

	@Resource
	private MallShopService mallShopService;

	@Resource
	private MallProductService mallProductService;

	@Resource
	private MallProductSpecService mallProductSpecService;

	@Resource
	private UserBaseService userBaseService;

	@Override
	protected BaseService<MallOrder> getBaseService() {
		return mallOrderService;
	}

	/**
	 * 商城/圈商-确认订单
	 * 
	 * @param mallOrderVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doAdd")
	@ResponseBody
	public Result doAdd(@RequestBody MallOrderVo mallOrderVo) {
		Result result = new Result();
		OrderBase orderBase = new OrderBase();
		UserAddressVo userAddress = null;
		MallShopVo shop = null;
		UserBase curUser = userBaseService.getById(super.getUserId());// 当前用户
		if (curUser.getCommunityId() == null) {
			result.addErr("请选加入社区！");
			return result;
		}
		// 校验基础数据
		if (mallOrderVo == null) {
			result.addErr("参数不能为空");
		} else {
			OrderItem orderItem = mallOrderVo.getOrderItems().get(0);
			MallProduct mallProduct = mallProductService.getProductBySpecId(orderItem.getProductId());
			shop = mallShopService.getById(mallProduct.getShopId());
			mallOrderVo.setShopId(shop.getId());
			if (mallOrderVo.getShopId() == null) {
				result.addErr("店铺参数错误");
				return result;
			}
			if (shop == null) {
				result.addErr("店铺不存在");
				return result;
			} else if (shop.getCreatorId().intValue() == super.getUserId().intValue()) {
				result.addErr("不能在自己的店铺下单");
				return result;
			}
			if (mallOrderVo.getOrderType() == null) {
				result.addErr("订单类型错误");
			} else if (mallOrderVo.getDeliveryType().intValue() != MallShopSendDeliveryTypeDictEnum.BUYERPICKUP
					.getCode() && mallOrderVo.getAddressId() == null) {
				result.addErr("请选择收货地址");
			} else if (mallOrderVo.getDeliveryType().intValue() == MallShopSendDeliveryTypeDictEnum.SELLERSEND.getCode()
					|| mallOrderVo.getDeliveryType().intValue() == MallShopSendDeliveryTypeDictEnum.QQUANSEND
							.getCode()) {
				// 获取地址信息
				userAddress = userAddressService.getById(mallOrderVo.getAddressId());
				if (userAddress != null) {
					if (userAddress.getCommunityId() == null) {
						result.addErr("地址信息不完整，请重新编辑您的地址");
					} else {
						if (mallOrderVo.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()
								&& mallOrderVo.getShopId() != null) {
							String extCommuityIds = shop.getExtCommunityIds();
							if (StringUtil.isBlank(extCommuityIds)) {
								if (shop.getCommunityId().intValue() != userAddress.getCommunityId().intValue()) {
									result.addErr("所选地址和店铺不在同一个社区");
								}
							} else {
								if (extCommuityIds.indexOf(String.valueOf(userAddress.getCommunityId())) < 0) {
									result.addErr("所选地址不在店铺的服务社区范围");
								}
							}

						}
					}
				} else {
					result.addErr("地址不存在了");
				}
			}
			if (mallOrderVo.getOrderItems() == null) {
				result.addErr("订单商品不存在");
			}
			if (mallOrderVo.getDeliveryType() == null) {
				result.addErr("请选择配送类型");
			}
			if (mallOrderVo.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()) {
				if (!shop.getHasBus()) {
					result.addErr("该店铺已暂停营业");
				}
			}
		}

		if (!result.checkForm()) {
			return result;
		}
		if (MallShopTypeDictEnum.QQMALLSHOP.getCode() == shop.getType()) {// 圈商
			mallOrderVo.setOrderType(OrderBaseOrderTypeDictEnum.QSHOP.getCode());
			orderBase.setShopId(shop.getId());
			orderBase.setSellerId(shop.getCreatorId());
		} else if (MallShopTypeDictEnum.SUPERMARKET.getCode() == shop.getType()) {// 商城
			mallOrderVo.setOrderType(OrderBaseOrderTypeDictEnum.QUANMALL.getCode());
			orderBase.setShopId(shop.getId());
			orderBase.setSellerId(null);
		}

		// 收货地址
		OrderDelivery orderDelivery = new OrderDelivery();
		orderDelivery.setDeliveryName("");
		orderDelivery.setDeliveryNo("");
		orderDelivery.setFreight(BigDecimal.ZERO);
		if (mallOrderVo.getDeliveryType().intValue() == MallShopSendDeliveryTypeDictEnum.BUYERPICKUP.getCode()) {
			// 自提
			orderDelivery.setType(OrderDeliveryTypeDictEnum.BUYERPICKUP.getCode());
			if (mallOrderVo.getOrderType() != null && mallOrderVo.getOrderItems() != null) {
				if (mallOrderVo.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QUANMALL.getCode()) {
					orderDelivery.setHasNeedDelivery(YesNoEnum.YES.getCode());
					MallSupplier supplier = mallSupplierService
							.getById(mallOrderVo.getOrderItems().get(0).getSupplierId());
					if (supplier != null) {
						if (StringUtil.isBlank(supplier.getName()) || StringUtil.isBlank(supplier.getPhone())
								|| StringUtil.isBlank(supplier.getAddress())) {
							result.addErr("门店信息不完整");
							return result;
						}
						orderDelivery.setConsignee(supplier.getName());
						orderDelivery.setPhone(supplier.getPhone());
						orderDelivery.setAddress(supplier.getAddress());
						if (super.getCommunityVisitId() != null && super.getCommunityVisitId().intValue() != 0) {
							orderBase.setCommunityId(super.getCommunityVisitId());
						} else {
							// 如果是自提订单或者是配送地址没有社区id信息，则使用当前访问的社区id
							if (userAddress != null && userAddress.getCommunityId() != null) {
								orderBase.setCommunityId(userAddress.getCommunityId());
							} else if (mallOrderVo.getVisitCommunityId() != null) {
								orderBase.setCommunityId(mallOrderVo.getVisitCommunityId());
							} else {// 如果当前的社区id信息不明确，则使用下单人所加入的社区id
								orderBase.setCommunityId(curUser.getCommunityId());
							}
						}
					} else {
						result.addErr("供应商信息不存在");
						return result;
					}
				} else if (mallOrderVo.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()) {
					orderDelivery.setHasNeedDelivery(YesNoEnum.NO.getCode());
					if (shop != null && shop.getId() != null) {
						if (StringUtil.isBlank(shop.getName()) || StringUtil.isBlank(shop.getPhone())
								|| StringUtil.isBlank(shop.getAddress())) {
							result.addErr("店铺信息不完整");
							return result;
						}
						orderDelivery.setConsignee(shop.getName());
						orderDelivery.setPhone(shop.getPhone());
						orderDelivery.setAddress(shop.getAddress());
						if (super.getCommunityVisitId() != null && super.getCommunityVisitId().intValue() != 0) {
							orderBase.setCommunityId(super.getCommunityVisitId());
						} else {
							// 如果是自提订单或者是配送地址没有社区id信息，则使用当前访问的社区id
							if (userAddress != null && userAddress.getCommunityId() != null) {
								orderBase.setCommunityId(userAddress.getCommunityId());
							} else if (mallOrderVo.getVisitCommunityId() != null) {
								orderBase.setCommunityId(mallOrderVo.getVisitCommunityId());
							} else {// 如果当前的社区id信息不明确，则使用下单人所加入的社区id
								orderBase.setCommunityId(curUser.getCommunityId());
							}
						}
					} else {
						result.addErr("店铺信息不存在");
						return result;
					}
				}
			} else {
				result.addErr("订单信息不完整");
				return result;
			}
		} else {
			// 卖家发货, 获取地址信息
			if (userAddress == null) {
				userAddress = userAddressService.getById(mallOrderVo.getAddressId());
			}
			orderDelivery.setType(OrderDeliveryTypeDictEnum.SELLERSEND.getCode());
			if (mallOrderVo.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()) {
				if (mallOrderVo.getDeliveryType() == MallShopSendDeliveryTypeDictEnum.SELLERSEND.getCode()) {
					orderDelivery.setSendDeliveryType(OrderDeliverySendDeliveryTypeDictEnum.SELLER.getCode());
					orderDelivery.setFreight(shop.getFreight());
				} else if (mallOrderVo.getDeliveryType() == MallShopSendDeliveryTypeDictEnum.QQUANSEND.getCode()) {
					orderDelivery.setSendDeliveryType(OrderDeliverySendDeliveryTypeDictEnum.QUANQUAN.getCode());
					String freightStr = mallOrderService.getFreight(MallConst.PARAMKEY_ORDER_DELIVERY_QQFREIGHT);
					orderDelivery.setFreight(new BigDecimal(freightStr));
				}
			}
			orderDelivery.setConsignee(userAddress.getContactName());
			orderDelivery.setPhone(userAddress.getContactPhone());
			orderDelivery.setAddress(userAddress.getAddress());
			orderBase.setCommunityId(userAddress.getCommunityId());
		}
		// 订单基础信息
		orderBase.setTotal(BigDecimal.ZERO);
		orderBase.setBuyerId(super.getUserId());
		orderBase.setImg(mallOrderVo.getOrderItems().get(0).getImg());
		orderBase.setOrderType(mallOrderVo.getOrderType());
		orderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode());
		orderBase.setOrderStatusAt(TimeUtil.now());
		orderBase.setPayType(OrderBasePayTypeDictEnum.ONLINE.getCode());
		orderBase.setPayStatus(OrderBasePayStatusDictEnum.UNPAYED.getCode());
		orderBase.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.UNSEND.getCode());
		orderBase.setDeliveryStatusAt(TimeUtil.now());
		orderBase.setReturnStatus(OrderBaseReturnStatusDictEnum.NONEED.getCode());
		orderBase.setReturnStatusAt(TimeUtil.now());
		orderBase.setIsCallBack(YesNoEnum.NO.getCode());
		if (StringUtil.isNotBlank(mallOrderVo.getRemark())) {
			orderBase.setRemark(mallOrderVo.getRemark());
		}
		// 未付款情况下自动失效时间 60分钟后
		String returnStr = mallOrderService.getAutoExpireTime(OrderConst.DICTYPE_ORDER_ONLINE_PAY_AUTO_EXPIRE_MINS);
		if (StringUtil.isNotBlank(returnStr)) {
			Integer time = Integer.valueOf(returnStr);
			orderBase.setAutoExpireAt(TimeUtil.addMins(TimeUtil.now(), time));
		}
		String zeroFlag = "" + YesNoEnum.NO.getCode();
		try {
			result = mallOrderService.handleSaveOrder(orderBase, orderDelivery, mallOrderVo.getOrderItems(),
					mallOrderVo);
			String orderNo = result.get("orderNo").toString();
			if (StringUtil.isNotBlank(orderNo)) {
				OrderBase newOrderBase = orderBaseService.getByOrderNo(orderNo);
				if (newOrderBase != null && (newOrderBase.getTotal() == null
						|| BigDecimal.ZERO.compareTo(newOrderBase.getTotal()) == 0)) {
					zeroFlag = "" + YesNoEnum.YES.getCode();
				}
			}
		} catch (OrderException e) {
			e.printStackTrace();
		}
		result.put("zeroFlag", zeroFlag);
		return result;
	}

	/**
	 * 商城-订单取消
	 * 
	 * @param mallOrderVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doCancel")
	@ResponseBody
	public Result doCancel(@RequestBody MallOrderVo mallOrderVo) {
		Result result = new Result();
		try {
			if (StringUtil.isBlank(mallOrderVo.getOrderNo())) {
				result.addErr("参数错误");
				return result;
			}
			OrderBase orderBase = orderBaseService.getByOrderNo(mallOrderVo.getOrderNo());
			if (orderBase == null) {
				result.addErr("订单不存在");
				return result;
			}
			if (orderBase.getBuyerId().intValue() != super.getUserId().intValue()) {
				result.addErr("权限错误");
				return result;
			}
			result = mallOrderService.handleCancelOrder(orderBase.getOrderNo());

		} catch (OrderException e) {
			// TODO 下单异常
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 商城-订单取消
	 * 
	 * @param mallOrderVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doDelete")
	@ResponseBody
	public Result doDelete(@RequestBody MallOrderVo mallOrderVo) {
		Result result = new Result();
		return result;
	}

	/**
	 * 获取店铺参数
	 * 
	 * @param mallShop
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/getDisParam")
	@ResponseBody
	public Result getDisParam(@RequestBody MallShop mallShop) {
		Result result = new Result();
		String freeDeliverValue = "0";// 店铺配送起送金额
		String shopFreight = "0";// 店铺配送费
		String quanDeliverValue = "0";// 社区店铺圈圈配送起送金额
		String quanFreight = "0";// 社区店铺圈圈配送费
		if (mallShop.getId() == null) {
			mallShop.setId(1);
		}
		MallShop shop = mallShopService.getById(mallShop.getId());
		if (shop == null) {
			result.addErr("店铺参数错误");
			return result;
		}
		if (shop.getType().intValue() == MallShopTypeDictEnum.SUPERMARKET.getCode()) {
			freeDeliverValue = mallOrderService.getFreeDeliverValue(MallConst.PARAMKEY_MALL_FREE_DELIVER_VALUE);
			// 满减信息
			SalesBaseVo salesBase = salesBaseService.getByTarget(SalesBaseTargetDictEnum.ONESHOP.getCode(),
					shop.getId());
			if (salesBase != null) {
				result.put("sales", salesBase);
			}
		} else if (shop.getType().intValue() == MallShopTypeDictEnum.QQMALLSHOP.getCode()) {
			if (shop.getDeliveryValue() != null) {
				freeDeliverValue = shop.getDeliveryValue().toString();
				result.put("sendDeliveryType", shop.getSendDeliveryType());
			}
			if (shop.getSendDeliveryType().indexOf("2") > -1 && shop.getFreight() != null) {
				shopFreight = shop.getFreight().toString();
			}
			if (shop.getSendDeliveryType().indexOf("3") > -1) {
				if (MallShopStyleDictEnum.QQSTORE.getCode() == shop.getStyle()) {// 便利店
					quanDeliverValue = mallOrderService
							.getFreeDeliverValue(MallConst.PARAMKEY_QSTORE_FREE_DELIVER_VALUE);
					quanFreight = mallOrderService.getFreeDeliverValue(MallConst.PARAMKEY_ORDER_DELIVERY_QQFREIGHT);
				} else {
					quanDeliverValue = mallOrderService
							.getFreeDeliverValue(MallConst.PARAMKEY_QSHOP_FREE_DELIVER_VALUE);
					quanFreight = mallOrderService.getFreeDeliverValue(MallConst.PARAMKEY_ORDER_DELIVERY_QQFREIGHT);
				}

			}

			// 满减信息
			/*
			 * int target = 0; if(shop.getStyle().intValue() ==
			 * MallShopStyleDictEnum.VIRTUAL.getCode()){//邻里店 target =
			 * SalesBaseTargetDictEnum.NEISHOP.getCode(); }else
			 * if(shop.getStyle().intValue() ==
			 * MallShopStyleDictEnum.LOCAL.getCode()){//社区店铺 target =
			 * SalesBaseTargetDictEnum.COMSHOP.getCode(); }
			 */
			// 指定商家促销
			SalesBaseVo salesBase = salesBaseService.getByTarget(SalesBaseTargetDictEnum.ONESHOP.getCode(),
					shop.getId());
			if (salesBase != null) {
				result.put("sales", salesBase);
			}
		}
		result.put("freeDeliverValue", freeDeliverValue);
		result.put("freight", shopFreight);
		result.put("quanDeliverValue", quanDeliverValue);
		result.put("quanFreight", quanFreight);
		return result;
	}
}
